package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.huaweicloud.sdk.iotda.v5.model.ShowDeviceResponse;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.huawei.HuaweiToolUtils;
import com.zzyl.common.utils.huawei.ProductVo;
import com.zzyl.common.utils.huawei.DeviceDto;
import com.zzyl.nursing.vo.DeviceDetailVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.service.IDeviceService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.Map;
import java.util.UUID;

import static com.zzyl.common.constant.CacheConstants.CAPTCHA_CODE_KEY;
import static com.zzyl.common.constant.CacheConstants.HUAWEI_IOT_ALL_KEY;

/**
 * 产品模块Service业务层处理
 *
 * @author ruoyi
 * @date 2025-02-28
 */
@Service
public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> implements IDeviceService {
    @Autowired
    private DeviceMapper deviceMapper;

    @Autowired
    private HuaweiToolUtils huaweiToolUtils;
    @Qualifier("redisTemplate")
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 查询产品模块
     *
     * @param id 产品模块主键
     * @return 产品模块
     */
    @Override
    public Device selectDeviceById(Long id) {
        return getById(id);
    }

    /**
     * 查询产品模块列表
     *
     * @param device 产品模块
     * @return 产品模块
     */
    @Override
    public List<Device> selectDeviceList(Device device) {
        return this.lambdaQuery()
                .eq(ObjectUtil.isNotNull(device.getLocationType()), Device::getLocationType, device.getLocationType())
                .eq(ObjectUtil.isNotNull(device.getProductName()), Device::getDeviceName, device.getDeviceName())
                .eq(ObjectUtil.isNotNull(device.getDeviceName()), Device::getProductName, device.getProductName())
                .list();
    }

    /**
     * 新增产品模块
     *
     * @param device 产品模块
     * @return 结果
     */
    @Override
    public int insertDevice(Device device) {
        return save(device) ? 1 : 0;
    }

    /**
     * 修改产品模块
     *
     * @param device 产品模块
     * @return 结果
     */
    @Override
    public int updateDevice(Device device) {
        return updateById(device) ? 1 : 0;
    }

    /**
     * 批量删除产品模块
     *
     * @param ids 需要删除的产品模块主键
     * @return 结果
     */
    @Override
    public int deleteDeviceByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除产品模块信息
     *
     * @param id 产品模块主键
     * @return 结果
     */
    @Override
    public int deleteDeviceById(Long id) {
        return removeById(id) ? 1 : 0;
    }

    /**
     * 1.1 从物联网平台同步产品列表
     */
    @Override
    public void syncProductList() {
        //调用华为工具类，同步数据
        huaweiToolUtils.synProduct();
    }

    /**
     * 1.2 查询所有产品列表
     *
     * @return
     */
    @Override
    public List<ProductVo> allProduct() {
        List<ProductVo> productVos = (List<ProductVo>) redisTemplate.opsForValue().get(HUAWEI_IOT_ALL_KEY);
        return productVos;
    }

    /**
     * 1.3 注册设备
     *
     * @param deviceDto
     */
    @Override
    public void register(DeviceDto deviceDto) {
        if (deviceDto.getLocationType() == 0) {
            deviceDto.setPhysicalLocationType(-1);
        }
        //条件判断
        CondJu(deviceDto);
        //秘钥
        String secret = UUID.randomUUID().toString().replaceAll("-", "");
        //2.发送请求到华为云并返回设备id和设备密钥，在数据库中新增设备
        String productId = huaweiToolUtils.addProduct(deviceDto, secret);
        //设备数据保存到数据库
        //属性拷贝
        Device device = BeanUtil.toBean(deviceDto, Device.class);
        //设备id、设备绑定状态
        device.setIotId(productId);
        //秘钥
        device.setSecret(secret);
        //设备名称
        device.setNodeId(deviceDto.getNodeId());
        try {
            //3.存放在数据库中
            this.save(device);
        } catch (Exception e) {
            huaweiToolUtils.remove(device.getIotId());
            throw new BaseException("保存失败");
        }

    }


    /**
     * 1.5 查询设备详细数据
     *
     * @param iotId
     * @return
     */
    @Override
    public DeviceDetailVo queryDeviceDail(String iotId) {
        //1.先从数据库中查找数据
        Device device = this.lambdaQuery().eq(Device::getIotId, iotId).one();
        //2，判断是否为空
        if (ObjectUtil.isEmpty(device)) {
            return null;
        }
        //3.从华为云查找数据
        ShowDeviceResponse response = huaweiToolUtils.queryProduct(iotId);
        String status = response.getStatus();
        String activeTime = response.getActiveTime();
        //4.组装数据
        DeviceDetailVo detailVo = BeanUtil.toBean(device, DeviceDetailVo.class);
        LocalDateTime activeTimeData = getTime(activeTime);
        detailVo.setDeviceStatus(status);
        detailVo.setActiveTime(activeTimeData);
        return detailVo;
    }

    /**
     * 1.6 查看设备上报的数据
     *
     * @param iotId
     * @return
     */
    @Override
    public List<Map> queryServiceProperties(String iotId) {
        return huaweiToolUtils.queryServiceProperties(iotId);
    }

    /**
     * 删除设备
     *
     * @param iotId
     */
    @Override
    public void delete(String iotId) {
        //判断该设备是否还戴在老人身上
        Long count = this.lambdaQuery()
                .eq(Device::getLocationType, 0)
                .eq(Device::getIotId, iotId)
                .count();
        if (count > 0) {
            //代表还有则不能删除
            throw new BaseException("该设备老人还戴在身上");
        }
        //删除数据库
        this.lambdaUpdate()
                .eq(Device::getIotId, iotId)
                .remove();

        //删除华为云中的设备
        huaweiToolUtils.remove(iotId);
    }

    /**
     * 修改设备
     *
     * @param device
     */
    @Override
    @Transactional
    public void updateV(Device device) {
        //判断有没有数据
        if (ObjectUtil.isEmpty(device)) {
            throw new BaseException("数据异常");
        }

        //修改数据库
        this.lambdaUpdate()
                .eq(Device::getIotId, device.getIotId())
                .update(device);
        //修改设备
        try {
            huaweiToolUtils.updateProject(device.getIotId(), device.getDeviceName());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 条件判断
     *
     * @param deviceDto
     */
    private void CondJu(DeviceDto deviceDto) {
        //1.条件判断
        //1.1判断名称是否重复了
        //1.2判断设备id是否重复了
        int count = this.lambdaQuery()
                .eq(Device::getDeviceName, deviceDto.getDeviceName())
                .or()
                .eq(Device::getIotId, deviceDto.getNodeId())
                .count().intValue();
        //如果大于0就说明有值，有相同的就不能添加到华为云上
        if (count > 0) {
            throw new BaseException("设备id和设备名称其中一个重复了，请仔细检查");
        }
        //1.3判断同一个位置上是否有了设置
        //校验同一位置是否绑定了同一类产品
        LambdaQueryWrapper<Device> condition = new LambdaQueryWrapper<>();
        condition.eq(Device::getProductKey, deviceDto.getProductKey())
                .eq(Device::getLocationType, deviceDto.getLocationType())
                .eq(Device::getPhysicalLocationType, deviceDto.getPhysicalLocationType())
                .eq(Device::getBindingLocation, deviceDto.getBindingLocation());
        if (count(condition) > 0) {
            throw new BaseException("该老人/位置已绑定该产品，请重新选择");
        }
    }


    private LocalDateTime getTime(String activeTimeStr) {
        if (ObjectUtil.isEmpty(activeTimeStr)) {
            return null;
        }
        LocalDateTime activeTime = LocalDateTimeUtil.parse(activeTimeStr, DatePattern.UTC_MS_PATTERN);
        //日期时区转换
        activeTime = activeTime.atZone(ZoneId.from(ZoneOffset.UTC))
                .withZoneSameInstant(ZoneId.of("Asia/Shanghai"))
                .toLocalDateTime();

        return activeTime;
    }


}
